package com.hmdp.utils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{

    private final String name;

    private final StringRedisTemplate stringRedisTemplate;

    private static final String KEY_PREFIX = "lock:";

    private static final String ID_PREFIX = UUID.randomUUID().toString();

    //初始化lua文件,DefaultRedisScript是RedisScript的父类
    //stringRedisTemplate.execute()中需要传递RedisScript类型,可以将其父类DefaultRedisScript传递进去
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    //在静态代码块中初始化脚本
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        //会自动查找unlock.lua文件
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        //配置返回值
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }


    /**
     * 尝试获取锁
     * @param timeoutSec 锁持有的超时时间,过期后自动释放
     * @return
     */
    @Override
    public boolean tryLock(Long timeoutSec) {
        //获取线程标识
        String threadId = ID_PREFIX+Thread.currentThread().getId();

        //获取锁
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX+name, threadId, timeoutSec, TimeUnit.SECONDS);

        //Boolean会有拆箱的风险,用equals将可能的null值以false返回
        return Boolean.TRUE.equals(success);
    }

    /**
     * 释放锁
     */
    @Override
    public void unlock() {

       //调用lua脚本,完成判断和释放锁
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                //需要传递带有key的集合KEYS,使用Collections.singletonList()将值封装成一个list传入
                Collections.singletonList(KEY_PREFIX+name),
                ID_PREFIX+Thread.currentThread().getId());
    }




    /* *//**
     * 释放锁
     *//*
    @Override
    public void unlock() {
        //获取线程标识
        String threadId = Thread.currentThread().getId()+ID_PREFIX;
        //获取锁里面的标识
        String s = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        //二者比较,一致则代表获得此锁的线程和当前准备释放锁的线程是同一个,不会乱释放其他线程的锁
        //一致可以释放
        //不一致,则代表获得此锁的线程和当前准备释放锁的线程是不是同一个啥也不干
        if (s.equals(threadId)){
            //释放锁
            stringRedisTemplate.delete(KEY_PREFIX+name);
        }
    }*/
}
